package start.gui;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.GregorianCalendar;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;

import jaxb.messages.Folder;
import jaxb.messages.Resource;

import start.StrongBoxClient;
import start.gui.audio.Playback;
import virtualHD.VirtualHDException;

public class BoxPanel extends ImagePanel implements ActionListener{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static final String EXIT_CMD = "EXIT";
	private static final String UPLOAD_CMD = "UPLOAD";
	private static final String CHROLE_CMD = "CHROLE";
	private static final String CHFOLDER_CMD = "CHFOLDER";

	public BoxPanel(String imagePath,StrongBoxClient hd) {
		super(imagePath,hd);

		dwg = new BoxWorkerGenerator(sbc,this);
		
		downIcon = createIcon("/images/download.png");
		delIcon = createIcon("/images/delete.png");
		upIcon = createIcon("/images/upload.png");
		chIcon = createIcon("/images/friends.png");
		folderIcon = createIcon("/images/folder.png");

		jf = new JFileChooser();
		jf.setCurrentDirectory(new File("."));

		currentFolder = hd.getUserID();

		setLayout(new BorderLayout());
		add(makeFolderPanel(),BorderLayout.PAGE_START);
		add(makeStatusPanel(),BorderLayout.LINE_START);
		add(makeTablePanel(),BorderLayout.CENTER);


		exitButton = new JButton("EXIT");
		exitButton.setActionCommand(EXIT_CMD);
		exitButton.addActionListener(this);
		add(exitButton,BorderLayout.PAGE_END);	

		//we add a view of user folder

		Folder folder = new Folder();
		folder.setUserid(currentFolder); 
		try {
			Resource resources[] = sbc.view(folder);
			addRes2Table(resources);
		} catch (VirtualHDException e) {
			this.showPopup("WARNING", e.getMessage(), JOptionPane.WARNING_MESSAGE);
		}

		(new Playback("/sounds/lock.wav")).execute();

	}


	private JPanel makeStatusPanel(){
		JPanel panel = new JPanel();
		panel.setOpaque(false);
		panel.setLayout(new GridBagLayout());
		GridBagConstraints c = new GridBagConstraints();

		Font userFont = new Font(Font.DIALOG,Font.HANGING_BASELINE,20);

		c.gridx = 0;
		c.gridy = 0;
		c.insets = new Insets(5,5,5,0);
		JLabel userLabel = new JLabel(" LOGGED AS ");
		userLabel.setForeground(Color.RED);
		userLabel.setFont(userFont);
		panel.add(userLabel,c);

		JLabel userL = new JLabel(sbc.getUserID());
		userL.setForeground(Color.RED);
		userL.setFont(userFont);
		c.gridx = 0;
		c.gridy = 1;
		c.insets = new Insets(5,0,5,0);
		panel.add(userL,c);

		c.gridx = 0;
		c.gridy = 2;
		c.insets = new Insets(5,10,5,0);
		c.fill = GridBagConstraints.HORIZONTAL;

		JButton chroleB = new JButton("Change permits");
		chroleB.setIcon(chIcon);
		chroleB.setOpaque(true);
		chroleB.setActionCommand(CHROLE_CMD);
		chroleB.addActionListener(this);
		panel.add(chroleB,c);

		c.gridx = 0;
		c.gridy = 3;
		c.fill = GridBagConstraints.HORIZONTAL;

		JButton uploadButton = new JButton("  Upload a file  ");
		uploadButton.setIcon(upIcon);
		uploadButton.setSize(chroleB.getSize());
		uploadButton.setActionCommand(UPLOAD_CMD);
		uploadButton.addActionListener(this);
		uploadButton.setOpaque(true);

		panel.add(uploadButton,c);

		progressBar = new JProgressBar();
		progressBar.setString("NO TRANSFER");
		progressBar.setForeground(Color.RED);
		c.gridx = 0;
		c.gridy = 4;
		c.fill = GridBagConstraints.HORIZONTAL;
		panel.add(progressBar,c);

		return panel;
	}

	private JPanel makeFolderPanel(){
		Font folderFont = new Font(Font.DIALOG,Font.BOLD,17);

		JPanel panel = new JPanel();
		panel.setOpaque(false);

		panel.setLayout(new FlowLayout());

		dirL = new JLabel("Current folder: "+currentFolder);
		dirL.setOpaque(true);
		dirL.setBackground(new Color(0x00,0x00,0x00));
		dirL.setFont(folderFont);
		dirL.setForeground(new Color(0xDA,0xA5,0x20));
		panel.add(dirL,FlowLayout.LEFT);

		String folders[];
		try {
			folders = sbc.getUsers();
			folderList = new JComboBox(folders);
			folderList.setSelectedIndex(0);
		} catch (VirtualHDException e) {
			showPopup(e.getMessage(), "Warning", JOptionPane.WARNING_MESSAGE);
		}
		
		panel.add(folderList);

		JButton changeFolder = new JButton("Change current folder");
		changeFolder.setIcon(folderIcon);
		changeFolder.setActionCommand(CHFOLDER_CMD);
		changeFolder.addActionListener(this);
		panel.add(changeFolder);


		return panel;
	}
	
	public JProgressBar getProgressBar(){
		return this.progressBar;
	}

	private JPanel makeTablePanel(){
		JPanel panel = new JPanel();
		panel.setOpaque(false);

		model = new DefaultTableModel(); //model for this table
		table = new JTable(model);
		model.addColumn("Filename");
		model.addColumn("Lastmod");
		model.addColumn("Size(KB)");
		model.addColumn("Download");
		model.addColumn("Delete");

		Action dowloadA = new AbstractAction()
		{
			private static final long serialVersionUID = 1L;

			public void actionPerformed(ActionEvent e)
			{
				(new Playback("/sounds/button.wav")).execute();
				int modelRow = Integer.valueOf( e.getActionCommand() );
				String filename = (String)model.getValueAt(modelRow, 0); //get filename
				Folder folder = new Folder();
				folder.setUserid(currentFolder);
				Resource resource = new Resource();
				resource.setName("./downloads/"+filename);
				
				BoxWorker dw = dwg.getWorker();
				dw.setFolder(folder);
				dw.setMode(BoxWorker.DOWNLOAD);
				dw.setResource(resource);
				dw.execute();
			}
		};

		Action deleteA = new AbstractAction()
		{
			private static final long serialVersionUID = 1L;

			public void actionPerformed(ActionEvent e)
			{
				(new Playback("/sounds/button.wav")).execute();
				int modelRow = Integer.valueOf( e.getActionCommand() );
				String filename = (String)model.getValueAt(modelRow, 0);	//gets the file name
				Folder folder = new Folder();
				folder.setUserid(currentFolder);
				Resource resource = new Resource();
				resource.setName(filename);

				try {
					sbc.del(folder, resource);
					showPopup("INFO","Resource deleted!",JOptionPane.INFORMATION_MESSAGE);
					model.removeRow(modelRow);
				} catch (VirtualHDException e1) {
					showPopup("ERROR",e1.getMessage(),JOptionPane.ERROR_MESSAGE);
				}
			}
		};

		ButtonColumn downColumn = new ButtonColumn(table,dowloadA,3);
		ButtonColumn delColumn = new ButtonColumn(table,deleteA,4);
		table.setCellEditor(downColumn);
		table.setCellEditor(delColumn);

		JScrollPane scrollPane = new JScrollPane(table);
		//scrollPane.getViewport().setBackground(Color.BLACK);
		panel.add(scrollPane);

		return panel;
	}


	private void addRes2Table(Resource[] resources){
		while(model.getRowCount() > 0)
			model.removeRow(0);
		
		for(int i=0;i<resources.length;i++){
			Object data[] = {resources[i].getName(),
					resources[i].getLastMod(),
					Float.toString((float)resources[i].getSize()/1024),
					downIcon,delIcon};
			model.addRow(data);
		}
	}
	
	public String getCurrentFolder(){
		return this.currentFolder;
	}
	
	public void addSingleResource2Table(Resource res){
		Object data[] = {res.getName(),
				res.getLastMod(),
				Float.toString((float)res.getSize()/1024),
				downIcon,delIcon};
		model.addRow(data);
	}

	@Override
	public void actionPerformed(ActionEvent evt) {
		if(evt.getActionCommand().equals(EXIT_CMD)){//exit
			try {
				sbc.closeHD();
				(new Playback("/sounds/close.wav")).execute();
			} catch (VirtualHDException e) {
				showPopup("ERROR",e.getMessage(),JOptionPane.ERROR_MESSAGE);
			}
			JFrame frame = (JFrame)SwingUtilities.getRoot(this);
			frame.setContentPane(new LoginPanel("/images/cassaforte.jpg",sbc));
			frame.validate();
		}else if(evt.getActionCommand().equals(UPLOAD_CMD)){
			(new Playback("/sounds/button.wav")).execute();

			int choice = jf.showDialog(this,"File to send:");
			if(choice == JFileChooser.APPROVE_OPTION){
				File f = jf.getSelectedFile();
				Folder folder = new Folder();
				folder.setUserid(currentFolder);
				Resource resource = new Resource();
				resource.setName(f.getAbsolutePath());
				resource.setSize((f.length()/1024));
				GregorianCalendar gc = new GregorianCalendar();
				gc.setTimeInMillis(System.currentTimeMillis());
				try {
					resource.setLastMod(DatatypeFactory.newInstance().newXMLGregorianCalendar(gc));
				} catch (DatatypeConfigurationException e1) {
					e1.printStackTrace();
				}
				
				BoxWorker dw = dwg.getWorker();
				dw.setFolder(folder);
				dw.setResource(resource);
				dw.setMode(BoxWorker.UPLOAD);
				dw.execute();
			}
		}else if(evt.getActionCommand().equals(CHFOLDER_CMD)){
			(new Playback("/sounds/button.wav")).execute();
			String f = (String)folderList.getSelectedItem();
			Folder folder = new Folder();
			folder.setUserid(f);
			try {
				Resource[] resources = sbc.view(folder);
				showPopup("INFO", "Directory changed!", JOptionPane.INFORMATION_MESSAGE);
				currentFolder = f;
				dirL.setText("Current folder: "+f);
				addRes2Table(resources);
			} catch (VirtualHDException e) {
				showPopup("ERROR", e.getMessage(), JOptionPane.ERROR_MESSAGE);
			}
		}else if(evt.getActionCommand().equals(CHROLE_CMD)){
			(new Playback("/sounds/button.wav")).execute();
			(new RoleFrame(sbc)).setVisible(true);
		}

	}


	private JTable table;
	private JComboBox folderList;
	private DefaultTableModel model;
	private JButton exitButton;
	private String currentFolder;
	private JProgressBar progressBar;
	private JFileChooser jf;

	private JLabel dirL;

	private ImageIcon downIcon;
	private ImageIcon delIcon;
	private ImageIcon upIcon;
	private ImageIcon chIcon;
	private ImageIcon folderIcon;
	
	private BoxWorkerGenerator dwg;

}
